package egovframework.npqs.pqi.mobile.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsonparser.ProdSearchThread;
import egovframework.npqs.pqi.mobile.jsonparser.ProdSearchThread.ProdSearchThreadCallback;

//품목결과검색(품목검색)
public class ProdDetailActivity extends Activity implements ProdSearchThreadCallback{
	private TextView titleTxt, navigation;
	private String prodCd;
	private EditText prodEdit;
	private ProdSearchThread prodThread;
	private ProdListAdapter prodAdapter;
	
	private AppStatus myapp;
	private Context context;
	private ListView listView;
	
	private ImageButton searchBtn, btnHome, btn_exit;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("품목결과검색");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_prod_detail);
		
		Intent intent = getIntent();
		prodCd = intent.getStringExtra("prodCd");
		
		init();
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus)context.getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("품목결과검색");
		/*btnLogin = (ImageButton)findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(ProdDetailActivity.this, "하이", Toast.LENGTH_SHORT).show();
			}
		});*/
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		System.out.println("eifj :: "+AppStatus.navigation.toString());
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		searchBtn = (ImageButton)findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				myapp.utilm.InputKeybordHidden(context, prodEdit);
				searchProd();
			}
		});
		
		prodEdit = (EditText)findViewById(R.id.edit_prod);
		
		listView = (ListView)findViewById(R.id.quarantine_list);
		prodAdapter = new ProdListAdapter();
		
		if(!prodCd.equals("no")){
			prodEdit.setText(prodCd);
			dateLoad();
		}
	}
	
	private void searchProd(){
		if(prodEdit.getText().toString().equals("")){
			myapp.utilm.ShowDialog(ProdDetailActivity.this, "실패", "품목코드를 입력해주세요.", 20);
		}else{
			dateLoad();
		}
	}
	
	private void dateLoad(){
		myapp.showDialogNo(context);	// 페이지가 로드 될때 다이얼로그 출력.
		temp = "검색";
		//asyncTaskIsConnectedVPN();
		threadStart();
		
	}

	public void threadStart(){
		if("검색".equals(temp)){
    		prodThread = new ProdSearchThread(context, this, prodEdit.getText().toString()
    				, AppStatus.getmUserId());
    		prodThread.start();
    	}
	}
	
	@Override
	public void OnProdSearchCompleted(boolean isNetworkConntected,
			boolean results, String message) {
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(results) {
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
		
	}

	@Override
	public void OnProdSearchError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
		
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				/*if(myapp.getArrProdSearchItem().size() == 1){
					returnToActivity();
				}else{
					prodAdapter.notifyDataSetChanged();
					listView.setAdapter(prodAdapter);	
				}*/
				prodAdapter.notifyDataSetChanged();
				listView.setAdapter(prodAdapter);
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				prodAdapter.notifyDataSetChanged();
				listView.setAdapter(prodAdapter);
				
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(context, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
/*	private void returnToActivity(){
		Intent intent = new Intent();
		intent.putExtra("prdCode", myapp.getArrProdSearchItem().get(0).getPrdlstCode());
		intent.putExtra("korNm", myapp.getArrProdSearchItem().get(0).getKorNm());
		intent.putExtra("hsCd", myapp.getArrProdSearchItem().get(0).getHsCd());
		setResult(1, intent);
		finish();
	}
*/	
	class ProdListAdapter extends BaseAdapter {
		TextView prod_code, prod_kor_nm, hs_code, korea_nm, prod_eng_nm, prod_bot_nm;

		@Override
		public int getCount() {
			return myapp.getArrProdSearchItem().size();
		}

		@Override
		public Object getItem(int position) {
			return myapp.getArrProdSearchItem().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_prod_search_item, parent, false);
    		}
			
			prod_code = (TextView)convertView.findViewById(R.id.prod_code);				//품목코드
			prod_kor_nm = (TextView)convertView.findViewById(R.id.korea_nm);		//품목명
			hs_code = (TextView)convertView.findViewById(R.id.hs_code);					//hs코드
			korea_nm = (TextView)convertView.findViewById(R.id.prod_kor_nm);				//한글명
			prod_eng_nm = (TextView)convertView.findViewById(R.id.prod_eng_nm);		//명문명
			//prod_bot_nm = (TextView)convertView.findViewById(R.id.prod_bot_nm);		//학명
			
			prod_code.setText(myapp.getArrProdSearchItem().get(position).getPrdlstCode());
			prod_kor_nm.setText(myapp.getArrProdSearchItem().get(position).getPrdlstNm());
			hs_code.setText(myapp.getArrProdSearchItem().get(position).getHsCd());
			korea_nm.setText(myapp.getArrProdSearchItem().get(position).getKorNm());
			prod_eng_nm.setText(myapp.getArrProdSearchItem().get(position).getEngNm());
			//prod_bot_nm.setText(myapp.getArrProdSearchItem().get(position).getBotNm());
			
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			/*if(!prodCd.equals("no")){
				Intent intent = new Intent();
				intent.putExtra("prdCode", myapp.getArrProdSearchItem().get(position).getPrdlstCode());
				intent.putExtra("korNm", myapp.getArrProdSearchItem().get(position).getKorNm());
				setResult(1, intent);
				finish();
			}else{
			}*/
			Intent intent = new Intent();
			intent.putExtra("prdlstCode", myapp.getArrProdSearchItem().get(position).getPrdlstCode());
			intent.putExtra("prdlstNm", myapp.getArrProdSearchItem().get(position).getPrdlstNm());
			intent.putExtra("hsCd", myapp.getArrProdSearchItem().get(position).getHsCd());
			intent.putExtra("korNm", myapp.getArrProdSearchItem().get(position).getKorNm());
			intent.putExtra("engNm", myapp.getArrProdSearchItem().get(position).getEngNm());
			setResult(1, intent);
			finish();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i("onDestroy()", "onDestroy()");
		AppStatus.navigation.delPathLocation();
	}
	
	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
}
